<?php
namespace app\http\middleware;

use app\models\User;

class CheckPermission
{
    const SUPER_ADMIN = 1; //超级1号员工，不需要监权
    /**
     * 排除的controller
     */
    protected static $exclude = [
        'Admin.auth',
    ];

    public function handle($request, \Closure $next)
    {
        $rule = $this->checkRule($request->path(), $request->method());

        if ($request->session('admin_login_id') != self::SUPER_ADMIN) {
            if (!in_array($request->controller(), self::$exclude) && !$rule) {
                if ($request->isAjax()) {
                    return json([
                        'ret'  => 10086,
                        'msg'  => '对不起，你没有权限',
                        'data' => [
                            'token' => $request->token('_token')
                        ]
                    ]);
                }
                return view('admin/auth', ['siteTitle' => '后台管理', 'meta' => []]);
            }
        }

        return $next($request);
    }

    /**
     * 对应预设规则的model/controller/method来交集匹配
     * @param $path
     * @param $method
     * @return bool
     */
    protected function checkRule($path, $method)
    {
        $uid = session('admin_login_id');
        $user = User::with(['roles', 'roles.permissions'])->find($uid);
        $permissions = $user->roles[0]->permissions ?? [];
        if ($permissions) {
            $pathArr = explode('/', $path);
            foreach ($permissions as $permission) {
                $uriArr = explode('/', $permission->auth->uri);
                $authMethod = $permission->auth->method ?? '';
                /** 判断是否启用、是否对应的method 再匹配对应的uri */
                if ($permission->status && $method == $authMethod && count(array_intersect($pathArr, $uriArr)) >= 3) {
                    return true;
                }
            }
        }
        return false;
    }
}
